﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using RN.ERP.Web.ModelService;
using System.Web.UI;
using System.Data;

namespace RN.ERP.Web
{
    public class UtilitiesTool
    {
        #region Session相关功能

        /// <summary>
        /// 重构Session。
        /// </summary>
        public static void RebuildSessionUserInfo()
        {
            if (HttpContext.Current.Request.Cookies[CookieConstant.COOKIE_USERGUID] != null)
            {
                string userGuid = HttpContext.Current.Request.Cookies[CookieConstant.COOKIE_USERGUID].Value;
                BasicService.BasicServiceClient client = new BasicService.BasicServiceClient();
                UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(client.DoLoginWithUGuid(userGuid, string.Empty, HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString()));
                if (userInfo.Result)
                {
                    SessionUserInfo sui = new SessionUserInfo();
                    sui.UserName = userInfo.UserName;
                    sui.Name = userInfo.Name;
                    sui.CorpUserGuid = userInfo.UserGuid;
                    sui.DogId = userInfo.DogId;
                    sui.RoleId = userInfo.RoleId;
                    sui.FuncPerm = userInfo.FuncPerm;
                    sui.AreaCode = userInfo.AreaCode;
                    sui.LocalArea = userInfo.AreaCode2;
                    sui.RoleType = userInfo.RoleType;
                    sui.RoleTypeTitle = userInfo.RoleTypeTitle;
                    sui.CurrentArea = string.IsNullOrEmpty(userInfo.AreaCode) ? string.Empty : userInfo.AreaCode.Substring(0, 2);
                    HttpContext.Current.Session[SessionConstant.SESSION_USERINFO] = sui;
                    ////当前市场范围，暂时处理,外地企业则需要首次登陆时确定市场范围
                    ////用SessionUserInfo.CurrentArea替代。
                    ////HttpContext.Current.Session[SessionConstant.SESSION_CURRENT_AREACODE] = userInfo.AreaCode;
                }
            }
        }

        /// <summary>
        /// 清理Session。
        /// </summary>
        public static void ClearSessionUserInfo()
        {
            HttpContext.Current.Session[SessionConstant.SESSION_USERINFO] = null;
            // Request.Cookies[CookieConstant.COOKIE_USERGUID].Value = string.Empty;
            if (HttpContext.Current.Request.Cookies[CookieConstant.COOKIE_USERGUID] != null)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieConstant.COOKIE_USERGUID];
                cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Set(cookie);
                HttpContext.Current.Request.Cookies.Remove(CookieConstant.COOKIE_USERGUID);
            }
        }

        #endregion

        #region JS弹出窗体

        /// <summary>
        /// 正常弹框提示
        /// </summary>
        /// <param name="message"></param>
        public static void Show(string message)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "')" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "ShowMessage", script);
            //page.RegisterClientScriptBlock("ShowMessage", script);
        }

        /// <summary>
        /// 弹出信息框后退
        /// </summary>
        /// <param name="message"></param>
        public static void ShowAndBack(string message)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "');javascript:history.back(1)" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }
        public static void GoBack()
        {
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "javascript:history.back(1)" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }

        /// <summary>
        /// 正常弹框提示且跳转指定页面
        /// </summary>
        /// <param name="message"></param>
        /// <param name="url"></param>
        public static void ShowAndRedirect(string message, string url)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "');window.self.location = \"" + url + "\";" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;

            page.ClientScript.RegisterStartupScript(page.GetType(), "", script);
        }
        public static void ShowAndRefresh(string message)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "'); try{location.href=location.href;}catch(err){};";
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.ClientScript.RegisterStartupScript(page.GetType(), "ShowAndRedirect", script);

        }
        public static void ShowAndRefreshParent(string message)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "'); try{opener.location=opener.location.href;}catch(err){parent.location=parent.location.href;};window.close();";
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }
        public static void ShowAndRefreshParentRoot(string message)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "'); try{opener.location=opener.location.href;}catch(err){parent.parent.location=parent.parent.location.href;};window.close();";
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }
        /// <summary>
        /// 正常弹框提示且关闭当前窗口
        /// </summary>
        /// <param name="message"></param>
        public static void ShowAndClose(string message)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.alert('" + message + "')" + System.Environment.NewLine;
            script += "window.close()" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }


        /// <summary>
        ///updatapanel弹框提示
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="msg"></param>
        public static void UpdateShow(Control ctrl, string msg)
        {
            ScriptManager.RegisterStartupScript(ctrl, ctrl.GetType(), "", "alert('" + msg + "')", true);
        }
        /// <summary>
        /// updatapanel弹框提示且跳转指定页面
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="msg"></param>
        /// <param name="url"></param>
        public static void UpdateShowAndRedirect(Control ctl, string msg, string url)
        {
            ScriptManager.RegisterStartupScript(ctl, ctl.GetType(), "", "alert('" + msg + "');window.self.location = '" + url + "';", true);
        }

        /// <summary>
        /// 弹出信息框确认后跳转到页面1，否则页面2
        /// </summary>
        /// <param name="message"></param>
        public static void confirmAndGo(string message, string url1, string url2)
        {
            message = message.Replace("\"", "\\\"");
            message = message.Replace("\'", "\\\'");
            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "if(confirm('" + message + "')){window.location='" + url1 + "';}else{window.location='" + url2 + "';}" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;
            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }

        public static void LigerAlert(Control control, string content)
        {
            ScriptManager.RegisterStartupScript(control, control.GetType(), "", "$.ligerDialog.warn('" + content + "');", true);
        }

        #region 弹出新页面
        /// <summary>
        /// 弹出新页面
        /// </summary>
        /// <param name="url">页面</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void ShowUrlWeb(string url, string width, string height)
        {

            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += " window.showModalDialog('" + url + "', null , 'center:yes;dialogHeight:" + height + "; dialogwidth:" + width + ";help:no;status: yes ; ')" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;
            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);

        }

        #endregion

        #region 弹出新页面
        /// <summary>
        /// 弹出新页面
        /// </summary>
        /// <param name="url">页面</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void OpenWindow(string url, int width, int height)
        {

            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.open('" + url + "','','width=" + width + "px,height=" + height + "px,scrollbars=1,top=50px,left=100px,resizable=yes');" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }


        public static void OpenNewWindow(string url)
        {

            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.open('" + url + "');" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            Page page = (Page)HttpContext.Current.Handler;
            page.RegisterStartupScript("", script);
        }

        /// <summary>
        /// 弹出新页面
        /// </summary>
        /// <param name="url">页面</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void OpenWindow(Control ctl, string url, int width, int height)
        {

            string script = "<script language='javascript'>" + System.Environment.NewLine;
            script += "window.open('" + url + "','','width=" + width + "px,height=" + height + "px,scrollbars=1,top=50px,left=100px,resizable=yes');" + System.Environment.NewLine;
            script += "</script>" + System.Environment.NewLine;

            ScriptManager.RegisterStartupScript(ctl, ctl.GetType(), "", script, true);
        }

        #endregion

        #endregion

        #region 其它

        /// <summary>
        /// 返回地区标题
        /// </summary>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public static string GetAreaTitle(object areaCode)
        {
            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length >= 2)
                {
                    var areaInfos = JsonConvert.DeserializeObject<List<a_AreaInfo>>(HttpContext.Current.Application[ApplicationConstant.APPLICATION_AREA].ToString());
                    var currentArea = areaInfos.Where(a => code.StartsWith(a.Code)).FirstOrDefault();
                    title = currentArea == null ? "" : currentArea.Title;
                }
            }
            return title;
        }

        /// <summary>
        /// 获取企业类型
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> CorpTypeDic
        {
            get
            {
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(HttpContext.Current.Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString());
            }
        }

        /// <summary>
        /// 响应输出内容。
        /// </summary>
        /// <param name="strData"></param>
        /// <param name="contentType"></param>
        public static void OutputData(string strData, string contentType)
        {
            if (string.IsNullOrEmpty(contentType))
            {
                HttpContext.Current.Response.ContentType = "text/plain";
            }
            else
            {
                HttpContext.Current.Response.ContentType = contentType;
            }
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(strData);
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 验证图片是否存在-返回未上传文件的funcCode
        /// </summary>
        /// <param name="sysCodes"></param>
        /// <param name="funcCodes"></param>
        /// <param name="filenm"></param>
        /// <returns></returns>
        public static string IsFileExists(string filenm, string sysCodes, string funcCodes)
        {
            string result = string.Empty;
            string[] fCodes = funcCodes.Split(',');
            //生成文件名
            string fileName = filenm;
            if (filenm.IndexOf(".jpg") > 0)
            {
                fileName = filenm.Replace(".jpg", "");
            }
            try
            {
                FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient();
                //文件存在性
                for (int i = 0; i < fCodes.Length; i++)
                {
                    if (string.IsNullOrEmpty(fCodes[i]))
                    {
                        continue;
                    }
                    ///判断是否有上传扫描件
                    if (fileService.GetFileList(fileName, sysCodes, fCodes[i]).Count == 0)
                    {
                        result = fCodes[i];
                        break;
                    }
                }
            }
            catch
            {
            }
            return result;
        }
        public static string IsImgFileExists(string filenms, string sysCodes, string funcCodes)
        {
            string result = string.Empty;
            string[] fCodes = funcCodes.Split(',');
            string[] fnames = filenms.Split(',');
            if (fCodes.Length != fnames.Length)
            {
                return result;
            }
            try
            {
                FileService.FileWebServiceSoapClient fileService = new FileService.FileWebServiceSoapClient();
                //文件存在性
                for (int i = 0; i < fCodes.Length; i++)
                {
                    if (string.IsNullOrEmpty(fCodes[i]) && string.IsNullOrEmpty(fnames[i]))
                    {
                        continue;
                    }
                    //生成文件名
                    string fileName = fnames[i];
                    if (fileName.IndexOf(".jpg") > 0)
                    {
                        fileName = fileName.Replace(".jpg", "");
                    }
                    ///判断是否有上传扫描件
                    if (fileService.GetFileList(fileName, sysCodes, fCodes[i]).Count == 0)
                    {
                        result = fCodes[i];
                        break;
                    }
                }
            }
            catch
            {
            }
            return result;
        }
        /// <summary>
        /// 从数据源生成DataTable
        /// </summary>
        /// <param name="statist"></param>
        /// <returns></returns>
        public static DataTable StructToDataTable(ModelService.StatisticsStruct statist)
        {
            DataTable result = new DataTable();
            if (statist.Header.Count() == 0)
            {
                return result;
            }
            foreach (ModelService.StatisticsStruct.StatisticsCell headerCell in statist.Header.LastOrDefault().HeaderCells)
            {
                result.Columns.Add(new DataColumn()
                {
                    ColumnName = headerCell.Value
                });
            }
            foreach (ModelService.StatisticsStruct.StatisticsRow row in statist.Data)
            {
                DataRow dr = result.NewRow();
                int index = 0;
                foreach (ModelService.StatisticsStruct.StatisticsCell cell in row.DataCells)
                {
                    dr[index] = cell.Value;
                    index++;
                }
                result.Rows.Add(dr);
            }
            return result;
        }

        /// <summary>
        /// 取得审核状态列表用于绑定审核状态选择下拉列表
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="areaCode"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetAllFlowStatus(string classId, string areaCode, string roleId)
        {
            try
            {
                using (BasicService.BasicServiceClient client = new BasicService.BasicServiceClient())
                {
                    string msg = string.Empty;
                    return JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetAllFlowStatus(out msg, areaCode, roleId, classId));
                }
            }
            catch
            {
                return null;
            }
        }


        #endregion

        #region 字符转义

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToHtml(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            //str = str.Replace(" ", "&nbsp;");
            //str = str.Replace("&", "&amp;");
            //str = str.Replace("\"", "&quot;");
            //str = str.Replace("<", "&lt;");
            //str = str.Replace(">", "&gt;");
            str = str.Replace("\n", "<br/>");

            return str;
        }

        //text替换
        public static string ToTXT(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&amp;", "&");
            str = str.Replace("&quot;", "\"");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&gt;", ">");
            str = str.Replace("<br/>", "\n");

            return str;
        }

        /// <summary>
        /// 数据加密显示。
        /// </summary>
        /// <param name="corpUserGuid">系统登录用户的GUID。</param>
        /// <param name="roleType">系统登录用户的类型。User:企业用户；Manager:主管部门。</param>
        /// <param name="currentUserGuid">待查的用户GUID。</param>
        /// <param name="inputString">输入文本。</param>
        /// <returns></returns>
        public static string GetEcryptStr(
            string corpUserGuid,
            string roleType,
            string currentUserGuid,
            string inputString)
        {
            if (inputString == null)
            {
                return "";
            }
            switch (roleType.ToLower())
            {
                case "user":
                    if (corpUserGuid.Trim() == currentUserGuid.Trim())
                    {
                        return inputString;
                    }
                    else
                    {
                        string ecryptedString = string.Empty;
                        if (inputString.Length > 3)
                        {
                            ecryptedString = inputString.Substring(0, 3);
                            for (int i = 0; i < inputString.Length - 3; i++)
                            {
                                ecryptedString += "*";
                            }
                            return ecryptedString;
                        }
                        else
                        {
                            return "***";
                        }
                    }
                case "manager":
                default:
                    return inputString;
            }
        }

        #endregion
    }
}